<template>
  <div class="house-renting">
    <div class="page-header">
      <h2>浏览房源</h2>
      <el-button type="primary" icon="el-icon-star-off" @click="showMyCollections">我的收藏</el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="房源标题或地址" clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="户型">
          <el-select v-model="searchForm.roomType" placeholder="请选择户型" clearable>
            <el-option label="一室一厅" value="一室一厅"></el-option>
            <el-option label="两室一厅" value="两室一厅"></el-option>
            <el-option label="三室两厅" value="三室两厅"></el-option>
            <el-option label="四室两厅" value="四室两厅"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租金范围">
          <el-input v-model.number="searchForm.minPrice" placeholder="最低价" style="width: 100px;" type="number"></el-input>
          <span style="margin: 0 5px;">-</span>
          <el-input v-model.number="searchForm.maxPrice" placeholder="最高价" style="width: 100px;" type="number"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 房源卡片列表 -->
    <div v-loading="loading" class="house-list">
      <el-row :gutter="20">
        <el-col :span="8" v-for="house in tableData" :key="house.id">
          <el-card class="house-card" shadow="hover">
            <div class="house-image">
              <el-image
                :src="house.coverImage || 'https://via.placeholder.com/300x200?text=No+Image'"
                fit="cover"
                style="width: 100%; height: 200px;"
              ></el-image>
              <el-tag class="house-tag" type="success" v-if="house.status === 1">在租</el-tag>
            </div>
            <div class="house-info">
              <h3 class="house-title" :title="house.title">{{ house.title }}</h3>
              <p class="house-address"><i class="el-icon-location-outline"></i> {{ house.address }}</p>
              <div class="house-meta">
                <span><i class="el-icon-s-home"></i> {{ house.roomType }}</span>
                <span><i class="el-icon-full-screen"></i> {{ house.area }}㎡</span>
                <span><i class="el-icon-view"></i> {{ house.viewCount || 0 }}</span>
              </div>
              <div class="house-price">
                <span class="price">¥{{ house.price }}</span>
                <span class="unit">/月</span>
              </div>
              <div class="house-actions">
                <el-button size="small" type="primary" plain @click="handleViewDetail(house)">查看详情</el-button>
                <el-button size="small" type="success" plain @click="handleAppointment(house)">预约看房</el-button>
                <el-button
                  size="small"
                  :type="house.isCollected ? 'warning' : 'info'"
                  :icon="house.isCollected ? 'el-icon-star-on' : 'el-icon-star-off'"
                  plain
                  @click="handleCollection(house)"
                >{{ house.isCollected ? '已收藏' : '收藏' }}</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-empty v-if="!loading && tableData.length === 0" description="暂无房源"></el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-box" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[9, 18, 30, 60]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 房源详情对话框 -->
    <el-dialog title="房源详情" :visible.sync="detailDialogVisible" width="70%" top="5vh">
      <div class="house-detail" v-loading="detailLoading">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-carousel height="400px" v-if="currentHouse.picList && currentHouse.picList.length > 0">
              <el-carousel-item v-for="(pic, index) in currentHouse.picList" :key="index">
                <el-image :src="pic.url" fit="cover" style="width: 100%; height: 100%;"></el-image>
              </el-carousel-item>
            </el-carousel>
            <el-empty v-else description="暂无图片" :image-size="200"></el-empty>
          </el-col>
          <el-col :span="12">
            <h2>{{ currentHouse.title }}</h2>
            <div class="detail-price">
              <span class="price">¥{{ currentHouse.price }}</span>
              <span class="unit">/月</span>
            </div>
            <el-divider></el-divider>
            <div class="detail-info">
              <el-row :gutter="20">
                <el-col :span="12"><strong>户型：</strong>{{ currentHouse.roomType }}</el-col>
                <el-col :span="12"><strong>面积：</strong>{{ currentHouse.area }}㎡</el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12"><strong>朝向：</strong>{{ currentHouse.orientation }}</el-col>
                <el-col :span="12"><strong>楼层：</strong>{{ currentHouse.floor }}/{{ currentHouse.totalFloor }}层</el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12"><strong>装修：</strong>{{ currentHouse.decoration }}</el-col>
                <el-col :span="12"><strong>浏览量：</strong>{{ currentHouse.viewCount || 0 }}</el-col>
              </el-row>
            </div>
            <el-divider></el-divider>
            <div class="detail-address">
              <p><i class="el-icon-location-outline"></i> <strong>地址：</strong>{{ currentHouse.address }}</p>
            </div>
            <div class="detail-facilities" v-if="currentHouse.facilities && currentHouse.facilities.length > 0">
              <p><strong>配套设施：</strong></p>
              <el-tag v-for="(facility, index) in currentHouse.facilities" :key="index" size="small" style="margin-right: 10px; margin-bottom: 10px;">
                {{ facility }}
              </el-tag>
            </div>
            <div class="detail-description">
              <p><strong>房源描述：</strong></p>
              <p>{{ currentHouse.description || '暂无描述' }}</p>
            </div>
            <div class="detail-actions" style="margin-top: 20px;">
              <el-button type="success" size="medium" @click="handleAppointment(currentHouse)">预约看房</el-button>
              <el-button type="primary" size="medium" @click="handleApply(currentHouse)">申请租房</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 预约看房对话框 -->
    <el-dialog title="预约看房" :visible.sync="appointmentDialogVisible" width="40%">
      <el-form :model="appointmentForm" :rules="appointmentRules" ref="appointmentForm" label-width="100px">
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            v-model="appointmentForm.appointmentTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="appointmentForm.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="appointmentForm.remark" :rows="3" placeholder="其他要求或说明"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="appointmentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAppointment">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'HouseRenting',
  data() {
    return {
      loading: false,
      detailLoading: false,
      searchForm: {
        keyword: '',
        roomType: '',
        minPrice: null,
        maxPrice: null
      },
      tableData: [],
      pageNo: 1,
      pageSize: 9,
      total: 0,
      detailDialogVisible: false,
      currentHouse: {},
      appointmentDialogVisible: false,
      appointmentForm: {
        houseId: null,
        appointmentTime: '',
        contactPhone: '',
        remark: ''
      },
      appointmentRules: {
        appointmentTime: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    loadData() {
      this.loading = true
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        keyword: this.searchForm.keyword || undefined,
        roomType: this.searchForm.roomType || undefined,
        minPrice: this.searchForm.minPrice || undefined,
        maxPrice: this.searchForm.maxPrice || undefined,
        status: 1 // 只查询已上架的房源
      }

      this.$network.getHouseList(params).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.records || []
          // 处理封面图片
          this.tableData.forEach(house => {
            if (house.picList && house.picList.length > 0) {
              house.coverImage = house.picList[0].url
            }
            // 处理facilities
            if (typeof house.facilities === 'string') {
              try {
                house.facilities = JSON.parse(house.facilities)
              } catch (e) {
                house.facilities = []
              }
            }
          })
          this.total = res.data.data.total || 0
          // TODO: 批量检查收藏状态
        } else {
          this.$message.error(res.data.message || '获取房源列表失败')
        }
      }).catch(error => {
        console.error('获取房源列表失败:', error)
        this.$message.error('获取房源列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    handleSearch() {
      this.pageNo = 1
      this.loadData()
    },
    handleReset() {
      this.searchForm = {
        keyword: '',
        roomType: '',
        minPrice: null,
        maxPrice: null
      }
      this.pageNo = 1
      this.loadData()
    },
    handleViewDetail(house) {
      this.detailDialogVisible = true
      this.detailLoading = true
      this.$network.getHouseDetail(house.id).then(res => {
        if (res.data.code === 200) {
          this.currentHouse = res.data.data
          // 处理facilities
          if (typeof this.currentHouse.facilities === 'string') {
            try {
              this.currentHouse.facilities = JSON.parse(this.currentHouse.facilities)
            } catch (e) {
              this.currentHouse.facilities = []
            }
          }
        } else {
          this.$message.error(res.data.message || '获取房源详情失败')
          this.detailDialogVisible = false
        }
      }).catch(error => {
        console.error('获取房源详情失败:', error)
        this.$message.error('获取房源详情失败')
        this.detailDialogVisible = false
      }).finally(() => {
        this.detailLoading = false
      })
    },
    handleAppointment(house) {
      // 获取用户信息
      const userInfo = localStorage.getItem('userInfo')
      if (!userInfo) {
        this.$message.error('请先登录')
        this.$router.push('/login')
        return
      }

      const user = JSON.parse(userInfo)
      this.appointmentForm = {
        houseId: house.id,
        appointmentTime: '',
        contactPhone: user.phone || '',
        remark: ''
      }
      this.appointmentDialogVisible = true
      this.detailDialogVisible = false
      this.$nextTick(() => {
        this.$refs.appointmentForm && this.$refs.appointmentForm.clearValidate()
      })
    },
    submitAppointment() {
      this.$refs.appointmentForm.validate(valid => {
        if (valid) {
          this.$network.createAppointment(this.appointmentForm).then(res => {
            if (res.data.code === 200) {
              this.$message.success('预约成功，请等待房东确认')
              this.appointmentDialogVisible = false
            } else {
              this.$message.error(res.data.message || '预约失败')
            }
          }).catch(error => {
            console.error('预约失败:', error)
            this.$message.error('预约失败')
          })
        }
      })
    },
    handleApply(house) {
      // 申请租房
      this.$prompt('请输入申请理由', '申请租房', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,200}$/,
        inputErrorMessage: '申请理由不能为空且不超过200字'
      }).then(({ value }) => {
        const params = {
          houseId: house.id,
          remark: value
        }
        this.$network.createApply(params).then(res => {
          if (res.data.code === 200) {
            this.$message.success('申请成功，请等待房东审核')
            this.detailDialogVisible = false
          } else {
            this.$message.error(res.data.message || '申请失败')
          }
        }).catch(error => {
          console.error('申请失败:', error)
          this.$message.error('申请失败')
        })
      }).catch(() => {})
    },
    handleCollection(house) {
      if (house.isCollected) {
        // 取消收藏
        this.$network.removeCollection(house.id).then(res => {
          if (res.data.code === 200) {
            this.$message.success('已取消收藏')
            house.isCollected = false
          } else {
            this.$message.error(res.data.message || '操作失败')
          }
        }).catch(error => {
          console.error('取消收藏失败:', error)
          this.$message.error('操作失败')
        })
      } else {
        // 添加收藏
        this.$network.addCollection({ houseId: house.id }).then(res => {
          if (res.data.code === 200) {
            this.$message.success('收藏成功')
            house.isCollected = true
          } else {
            this.$message.error(res.data.message || '操作失败')
          }
        }).catch(error => {
          console.error('添加收藏失败:', error)
          this.$message.error('操作失败')
        })
      }
    },
    showMyCollections() {
      this.$message.info('我的收藏功能开发中...')
      // TODO: 跳转到我的收藏页面或显示收藏列表
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.loadData()
    }
  }
}
</script>

<style scoped>
.house-renting {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.search-box {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.house-list {
  min-height: 400px;
}

.house-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.house-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.house-image {
  position: relative;
}

.house-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

.house-info {
  padding: 15px;
}

.house-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}

.house-address {
  font-size: 14px;
  color: #666;
  margin: 0 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.house-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
}

.house-meta span {
  display: flex;
  align-items: center;
}

.house-meta i {
  margin-right: 3px;
}

.house-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 15px;
}

.house-price .price {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.house-price .unit {
  font-size: 14px;
  color: #999;
  margin-left: 5px;
}

.house-actions {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.house-actions .el-button {
  flex: 1;
}

.pagination-box {
  margin-top: 20px;
  text-align: center;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}

.house-detail {
  padding: 20px;
}

.detail-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 20px;
}

.detail-price .price {
  font-size: 32px;
  font-weight: bold;
  color: #f56c6c;
}

.detail-price .unit {
  font-size: 16px;
  color: #999;
  margin-left: 8px;
}

.detail-info {
  line-height: 2;
}

.detail-info .el-row {
  margin-bottom: 10px;
}

.detail-address {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}

.detail-facilities {
  margin-bottom: 15px;
}

.detail-description {
  font-size: 14px;
  color: #666;
  line-height: 1.8;
}

.detail-description p {
  margin: 5px 0;
}
</style>

